/**
 * FileName: HexFieldEncoder
 * Author:   zhaoxiaoqiang
 * Date:     2019/8/21 8:05
 * Description: hex码转二进制
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.zxq.factory.encoder.impl;

import com.zxq.factory.encoder.IFieldEncoder;
import com.zxq.memory.ByteArrayPools;


/**
 * 〈hex码转二进制〉
 *
 * @author zhaoxiaoqiang
 * @date 2019/8/21
 * @since 1.0.0
 */

public class HexFieldEncoder implements IFieldEncoder<String> {



    @Override
    public byte[] encoder(String value, int len) {
        String hexValue = "";
        for(int i = 0; i < len; i++) {
           hexValue += "00";
        }
        String prefix =  hexValue.substring(0,hexValue.length() - value.length());
        hexValue = prefix + value;
        return toHex(hexValue);
    }

    private byte[] toHex(String hexStr) {
        hexStr = hexStr.length() % 2 != 0 ? "0" + hexStr : hexStr;
        byte[] b = ByteArrayPools.getBytes(hexStr.length() / 2 + "");
        for (int i = 0; i < b.length; i++) {
            int index = i * 2;
            int v = Integer.parseInt(hexStr.substring(index, index + 2), 16);
            b[i] = (byte) v;
        }
        return b;
    }








}
